package paginator

import "gorm.io/gorm"

type Pagination struct {
	PageParam
	Total int64       `json:"Total"`
	Data  interface{} `json:"Data"`
}

type PageParam struct {
	PageSize int `json:"PageSize"`
	Page     int `json:"Page"`
}

func Paginate(r *PageParam) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		page := r.Page
		if page == 0 {
			page = 1
		}

		pageSize := r.PageSize
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
